package com.lxy.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration
public class DataSourceConfig {

    @Value("${spring.datasource.driver-class-name}")
    private String jdbcDriver;
    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.username}")
    private String jdbcUser;
    @Value("${spring.datasource.password}")
    private String jdbcPassword;


    @Bean(name = "dataSource")
    @Qualifier(value = "dataSource")
    @Primary
    public DataSource dataSource() throws PropertyVetoException {
        DataSource dataSource = DataSourceBuilder.create().type(ComboPooledDataSource.class).build();

        ((ComboPooledDataSource) dataSource).setDriverClass(jdbcDriver);
        ((ComboPooledDataSource) dataSource).setJdbcUrl(jdbcUrl);
        ((ComboPooledDataSource) dataSource).setUser(jdbcUser);
        ((ComboPooledDataSource) dataSource).setPassword(jdbcPassword);

        ((ComboPooledDataSource) dataSource).setMaxPoolSize(30);
        ((ComboPooledDataSource) dataSource).setMinPoolSize(10);
        //关闭连接后不自动commit
        ((ComboPooledDataSource) dataSource).setAutoCommitOnClose(false);
        //获取连接超时时间
        ((ComboPooledDataSource) dataSource).setCheckoutTimeout(1000);
        //当获取连接失败重试次数
        ((ComboPooledDataSource) dataSource).setAcquireRetryAttempts(2);
        return dataSource;
    }

}
